package com.gutsyzhan.dynamicdatasourcespringbootstarter.creator;

import com.alibaba.druid.Constants;
import com.alibaba.druid.pool.DruidDataSource;
import com.gutsyzhan.dynamicdatasourcespringbootstarter.constants.DataSourceConstant;
import com.gutsyzhan.dynamicdatasourcespringbootstarter.properties.DataSourceProperty;

import javax.sql.DataSource;
import java.util.Objects;

public class DruidDataSourceCreator extends AbstractDataSourceCreator {
    @Override
    protected DataSource doCreateDataSource(DataSourceProperty dataSourceProperty) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(dataSourceProperty.getUsername());
        druidDataSource.setPassword(dataSourceProperty.getPassword());
        druidDataSource.setUrl(dataSourceProperty.getUrl());
        druidDataSource.setDriverClassName(dataSourceProperty.getDriverClassName());
        druidDataSource.configFromPropeties(dataSourceProperty.getDruidConfig().toProperties());

        try{
            druidDataSource.init();
        }catch (Exception e){
            throw new RuntimeException("druidDataSource create error,e=", e);
        }
        return druidDataSource;
    }

    @Override
    public boolean support(DataSourceProperty dataSourceProperty) {
        Class<? extends DataSource> type = dataSourceProperty.getType();
        return Objects.nonNull(type) && Objects.equals(type, DataSourceConstant.DRUID_DATASOURCE);
    }
}
